import { customRef } from 'vue';

/**
 * 防抖ref属性
 * @param value
 * @returns {ref}
 * @example
 */
function debounceRef(value: any) {
  let timer: string | number | NodeJS.Timeout | null | undefined = null;
  return customRef((track, trigger) => {
    return {
      get() {
        track();
        return value;
      },
      set(newValue) {
        if (timer) clearTimeout(timer);
        timer = setTimeout(() => {
          value = newValue;
          trigger();
        }, 1000);
      },
    };
  });
}

/**
 * 方法防抖
 * @param fn 防抖方法
 * @param delay 时间
 * @example const fn = debounce(() => {}, 1000);
 */
function debounceFunc<T extends (...args: any[]) => any>(fn: T, delay: number = 500): (...args: Parameters<T>) => void {
  let timer: NodeJS.Timeout | null = null;

  return function (this: any, ...args: Parameters<T>) {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn.apply(this, args);
      timer = null;
    }, delay);
  };
}

export { debounceRef, debounceFunc };
